package org.hscoder.websearcher.service;

import com.fasterxml.jackson.core.type.TypeReference;
import org.apache.commons.io.FileUtils;
import org.hscoder.websearcher.domain.EsFilm;
import org.hscoder.websearcher.domain.EsTags;
import org.hscoder.websearcher.repository.EsFilmRepository;
import org.hscoder.websearcher.repository.EsTagsRepository;
import org.hscoder.websearcher.util.JsonUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 电影条目信息导入程序
 */
@Component
public class EsFilmImporter {

    public static final Logger logger = LoggerFactory.getLogger(EsFilmImporter.class);

    @Autowired
    private EsFilmRepository filmRepository;
    @Autowired
    private EsTagsRepository tagsRepository;

    /**
     * 导入检索条件
     *
     * @param tagsFilePath
     * @return
     */
    public boolean importTags(String tagsFilePath) {

        try {
            String tagsContent = FileUtils.readFileToString(new File(tagsFilePath), "utf-8");

            EsTags tags = JsonUtil.fromJson(tagsContent, EsTags.class);

            tagsRepository.save(tags);
            return true;

        } catch (IOException e) {
            logger.error("read file {} failed", tagsFilePath, e);
            return false;
        }
    }

    /**
     * 从本地文件中导入电影信息
     *
     * @param detailDir
     * @return
     */
    public int importFilms(String detailDir) {

        List<EsFilm> esFilms = new ArrayList<>();

        //遍历文件
        for (File file : new File(detailDir).listFiles()) {

            try {

                //解析出EsFilm 对象实体
                String pageContent = FileUtils.readFileToString(file, "utf-8");
                List<EsFilm> pageFilms = JsonUtil.fromJson(pageContent, new TypeReference<List<EsFilm>>() {
                });

                AtomicInteger count = new AtomicInteger();

                if (pageFilms != null) {
                    pageFilms.stream().forEach(f -> {
                        if (!StringUtils.isEmpty(f.getName())) {
                            esFilms.add(f);
                            count.incrementAndGet();
                        }
                    });
                }

                logger.info("get {}/{} records from page {}", count.get(), pageFilms != null ? pageFilms.size() : 0, file.getName());
            } catch (IOException e) {
                logger.error("read file {} failed", file.getAbsolutePath(), e);
            }

        }

        //将 EsFilm 实体逐个入库
        esFilms.stream().forEach(f -> {

            filmRepository.save(f);

            logger.info("import film {}", f.getName());
        });
        return esFilms.size();
    }

}
